package com.zzyl.service.impl;

import com.google.common.collect.Lists;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;


    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {

        //1.远程调用根据登录授权码（userLoginRequestDto.getCode()）微信授权登录接口获取openId
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());
        //2.调用memberMapper根据openId查找member用用信息对象
        Member member = memberMapper.getByOpenId(openId);
        //3.判断用户信息是否为空，为空创建Member用户对象，封装openid
        if (member == null) {
            member = new Member();
            member.setOpenId(openId);
        }
        //4.远程调用根据手机号授权码（userLoginRequestDto.getPhoneCode()）微信获取手机号接口
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        //5.插入或更新
        if (member.getId() != null && !(member.getPhone().equals(phone))){
            //5.1 判断用户id不为空，并且获取的手机号与数据库查询到手机号不一致，封装最新的手机号再更新
            member.setPhone(phone);
            memberMapper.update(member);
        }
        if (member.getId() == null){
            //5.2 判断用户id为空进行插入操作
            //封装昵称
            int index = (int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size());
            String name = DEFAULT_NICKNAME_PREFIX.get(index) + phone.substring(7);
            member.setName(name);
            //封装手机号
            member.setPhone(phone);
            //插入操作，此处插入之后将生成的id返回
            memberMapper.save(member);
        }

        //6.生成jwt令牌token(载荷，签名，过期时间)
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID,member.getId());
        claims.put(Constants.JWT_USERNAME,member.getId());
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretkey(), jwtTokenManagerProperties.getTtl(), claims);
//        7.封装LoginVo对象（令牌和昵称）;
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(member.getName());
        loginVo.setToken(token);
        //8.返回loginVo
        return loginVo;
    }
}